import webapp2
import jinja2
import os
from google.appengine.api import users
from google.appengine.ext import ndb
import era
import country
import city
import time
import logging
import spreadsheet 
import person
import dic 
import labelcat



jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

    
class Archive(ndb.Model):
    user = ndb.StringProperty()
    id = ndb.TextProperty()
    era = ndb.TextProperty()
    country = ndb.TextProperty()
    desc = ndb.TextProperty()
    time = ndb.TextProperty()
    y = ndb.TextProperty()
    m = ndb.TextProperty()
 
class Index(webapp2.RequestHandler):
    def get(self, lang):
        archives = Archive.query(Archive.user == users.get_current_user().email())
        instance = dic.Operation()
        era_map = {}
        country_map = {}
        archive_labels = {}

        dics = instance.getDics(lang, labelcat.Cat.Era)
        for dic_entity in dics:
            era_map[dic_entity.name] = dic_entity.label   
        dics = instance.getDics(lang, labelcat.Cat.Country)
        for dic_entity in dics:
            country_map[dic_entity.name] = dic_entity.label
        dics = instance.getDics(lang, labelcat.Cat.ARCHIVE_OPERATION)
        for dic_entity in dics:
            archive_labels[dic_entity.name] = dic_entity.label      
        template_values = {
        'archives':archives,
        'lang':lang,
        'countryLabels':country_map,
        'eraLabels':era_map,
        'archive_labels':archive_labels
        }   
        template = jinja_environment.get_template('archive.html')
        self.response.out.write(template.render(template_values))


class AddPage(webapp2.RequestHandler):
    def get(self, lang):
        eras = era.Era.query()  
        instance = dic.Operation()
        era_label_map = {}
        operation_label_map = {}
        dics = instance.getDics(lang, labelcat.Cat.ARCHIVE_OPERATION)
        for dic_entity in dics:
            operation_label_map[dic_entity.name] = dic_entity.label
        dics = instance.getDics(lang, labelcat.Cat.Era)
        for dic_entity in dics:
            era_label_map[dic_entity.name] = dic_entity.label

   
        template_values = {
            'eras':eras,
            'lang':lang,
            'operationLabels':  operation_label_map,
            'eraLabels':  era_label_map           
        }
        template = jinja_environment.get_template('archive-create.html')
        self.response.out.write(template.render(template_values))

class ChooseCountryPage(webapp2.RequestHandler):
    def get(self, lang, era):
        countries = country.CountrySys.query(country.CountrySys.era == era) 
        operation_label_map = {}
        country_label_map = {}
        countryCultureMap = {}
        countryStyleMap = {}
        dic_instance = dic.Operation ()
        dics = dic_instance.getDics(lang, labelcat.Cat.ARCHIVE_OPERATION) 
        for dic_entity in dics:
            operation_label_map[dic_entity.name] = dic_entity.label
        dics = dic_instance.getDics(lang, labelcat.Cat.Country) 
        for dic_entity in dics:
            country_label_map[dic_entity.name] = dic_entity.label
        dics = dic_instance.getDics(lang, labelcat.Cat.COUNTRY_CULTURE) 
        for dic_entity in dics:
            countryCultureMap[dic_entity.name] = dic_entity.label
        dics = dic_instance.getDics(lang, labelcat.Cat.COUNTRY_STYLE) 
        for dic_entity in dics:
            countryStyleMap[dic_entity.name] = dic_entity.label
        template_values = {
            'lang':lang,
            'era':era,
            'countries':countries ,
            'operationLabels':operation_label_map,
            'countryLabels':country_label_map ,
            'countryCultureLabels':countryCultureMap,
            'countryStyleLabels':countryStyleMap
        }
        template = jinja_environment.get_template('archive-create-country-choose.html')
        self.response.out.write(template.render(template_values))



class Add(webapp2.RequestHandler):
    def get(self, lang, era_name, country_name):
        user_name = "AI"
        
        ISOTIMEFORMAT = "%Y-%m-%d %X"       
        time_str = time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))
        user = users.get_current_user().email()
        achive_keyname = era_name + "_" + country_name + "_" + user + "_" + time_str
        achive_key = ndb.Key("Archive", achive_keyname) 
        era_instance = era.Operation()   
        y = str(era_instance.getStartYear(era_name))
        m = "1";
        archives = Archive.query(ancestor=achive_key)
        for acrhive_element in archives:
            acrhive_element.key.delete
        logging.info("=========Create Archive")                
        logging.info("id:" + achive_keyname)      
        logging.info("era:" + era_name)                
        logging.info("country:" + country_name)                
        logging.info("Create time:" + time_str)                
        logging.info("y:" + y)                
        logging.info("m:" + m)                

        archive = Archive(key=achive_key, id=achive_keyname, user=users.get_current_user().email(),
                          era=era_name, country=country_name, time=time_str, y=y, m=m)
        archive.put()
        countries = country.CountrySys.query(country.CountrySys.era == era_name)
        for country_element in countries:
            country_key = ndb.Key("Country", achive_keyname + "_" + country_element.name)
            country_new = country.Country(key=country_key, name=country_element.name, culture=country_element.culture,
                                          style=country_element.style,
                                          era=country_element.era)              
            country_new.put() 
        spreadsheet_operation = spreadsheet.Operation()
        spreadsheet_feed = spreadsheet_operation.getFeed();
        gd_client = spreadsheet_operation.gd_client;  
        for i, spreadsheet_entry in enumerate(spreadsheet_feed.entry):
            spreadsheet_title = spreadsheet_entry.title.text      
            if "UDATA-CITY" == spreadsheet_title:
                spreadsheet_id_parts = spreadsheet_entry.id.text.split('/')
                spreadsheet_id = spreadsheet_id_parts[len(spreadsheet_id_parts) - 1]
                worksheet_feed = gd_client.GetWorksheetsFeed(spreadsheet_id);
                for j, worksheet_entry in enumerate(worksheet_feed.entry):
                    worksheet_title = worksheet_entry.title.text
                    worksheet_id_parts = worksheet_entry.id.text.split('/')
                    worksheet_id = worksheet_id_parts[len(worksheet_id_parts) - 1]
                    city_era = worksheet_title
                    if city_era == era_name:
                        list_feed = gd_client.GetListFeed(spreadsheet_id, worksheet_id)
                        for k, list_entry in enumerate(list_feed.entry):
                            city_country = list_entry.custom["country"].text
                            logging.info("country_name:" + country_name)
                            if city_country == country_name:
                                user_name = ""
                            else:
                                user_name = "AI"
                            city_name = list_entry.custom["name"].text
                            logging.info("city:" + city_name)

                            city_key = ndb.Key("City", user_name + "_" + achive_keyname + "_" + city_name)
                            city_latitude = int(list_entry.custom["latitude"].text)
                            city_longitude = int(list_entry.custom["longitude"].text)
                            city_country = list_entry.custom["country"].text
                            city_culture = list_entry.custom["culture"].text
                            city_entity = city.City(key=city_key, archive=user_name + "_" + achive_keyname,
                                                    name=city_name, culture=city_culture,
                                                    latitude=city_latitude, longitude=city_longitude,
                                                    country=city_country, era=city_era)              
                            city_entity.put()    
            elif "UDATA-PERSON-" + era_name == spreadsheet_title:
                logging.info("Person sheet:" + "UDATA-PERSON-" + era_name)
                spreadsheet_id_parts = spreadsheet_entry.id.text.split('/')
                spreadsheet_id = spreadsheet_id_parts[len(spreadsheet_id_parts) - 1]
                worksheet_feed = gd_client.GetWorksheetsFeed(spreadsheet_id);
                for j, worksheet_entry in enumerate(worksheet_feed.entry):
                    worksheet_title = worksheet_entry.title.text
                    worksheet_id_parts = worksheet_entry.id.text.split('/')
                    worksheet_id = worksheet_id_parts[len(worksheet_id_parts) - 1]
                    person_country = worksheet_title
                    logging.info("person country:" + worksheet_title)
                    list_feed = gd_client.GetListFeed(spreadsheet_id, worksheet_id)
                    for k, list_entry in enumerate(list_feed.entry):
                        person_name = list_entry.custom["name"].text
                        person_city = list_entry.custom["city"].text
                        person_culture = list_entry.custom["culture"].text
                        person_age = int(list_entry.custom["age"].text)
                        person_born = int(list_entry.custom["born"].text)
                        person_leadership = int(list_entry.custom["leadership"].text)
                        person_intelligence = int(list_entry.custom["intelligence"].text)
                        person_loyalty = int(list_entry.custom["loyalty"].text)
                        person_type = list_entry.custom["type"].text
                        if "King" == type:
                            person_loyalty = 99
                        if person_country == country_name:
                            user_name = ""
                        else:
                            user_name = "AI"
                        person_key = ndb.Key("Person", user_name + "_" + achive_keyname + "_" + person_name)

                        person_entity = person.Person(key=person_key, archive=achive_keyname, name=person_name,
                                                    city=person_city, age=person_age,
                                                    born=person_born, era=era_name, culture=person_culture,
                                                    leadership=person_leadership, intelligence=person_intelligence,
                                                    loyalty=person_loyalty, type=person_type)  
                        person_entity.put()          
        self.redirect("/" + lang + "/game/archive/" + achive_keyname + "/era/" + era_name + "/country/" + country_name)


